package com.jessefyz.module.task;

import com.jessefyz.common.task.Task;
import com.jessefyz.common.utils.BeanUtil;
import com.jessefyz.module.service.WxOrderService;
import com.jessefyz.module.shop.common.utils.OrderUtil;
import com.jessefyz.module.shop.constants.SystemConfig;
import com.jessefyz.module.shop.domain.LitemallOrder;
import com.jessefyz.module.shop.domain.LitemallOrderGoods;
import com.jessefyz.module.shop.service.ILitemallGoodsProductService;
import com.jessefyz.module.shop.service.ILitemallOrderGoodsService;
import com.jessefyz.module.shop.service.ILitemallOrderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Date;
import java.util.List;

public class OrderUnpaidTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);
    private long orderId = -1L;

    public OrderUnpaidTask(Long orderId, long delayInMilliseconds){
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Long orderId){
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);

        ILitemallOrderService orderService = BeanUtil.getBean(ILitemallOrderService.class);
        ILitemallOrderGoodsService orderGoodsService = BeanUtil.getBean(ILitemallOrderGoodsService.class);
        ILitemallGoodsProductService productService = BeanUtil.getBean(ILitemallGoodsProductService.class);
        WxOrderService wxOrderService = BeanUtil.getBean(WxOrderService.class);

        LitemallOrder order = orderService.getById(this.orderId);
        if(order == null){
            return;
        }
        if(!OrderUtil.isCreateStatus(order)){
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
        order.setCloseTime(new Date());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        Long orderId = order.getId();
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Long productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (productService.addStock(productId, number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }

        //返还优惠券
        wxOrderService.releaseCoupon(orderId.intValue());

        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}
